// ****************************************************************
// Copyright 2012, Stephan Burguchev
// e-mail: me@sburg.net
// ****************************************************************
// *
using System;
using System.Collections.Generic;
using System.Linq;
using System.Xml.Serialization;

namespace Updater.Common
{
    [XmlRoot("update-log")]
    public class UpdateLog
    {
        public UpdateLog()
        {
            this.AppliedUpdates = new UpdateInformation[0];
            this.ChangeLog = new ChangeLogRecord[0];
            this.ErrorDescription = "";
            this.ErrorDetalization = "";
        }

        [XmlArray("applied-updates")]
        [XmlArrayItem("update-information")]
        public UpdateInformation[] AppliedUpdates { get; set; }

        [XmlArray("change-log")]
        [XmlArrayItem("change-log-record")]
        public ChangeLogRecord[] ChangeLog { get; set; }

        [XmlElement("error-description")]
        public string ErrorDescription { get; set; }

        [XmlElement("error-detalization")]
        public string ErrorDetalization { get; set; }

        [XmlElement("install-date")]
        public DateTime InstallDate { get; set; }

        [XmlElement("succeed")]
        public bool Succeed { get; set; }

        public static UpdateLog CreateErrorLog(string errorDescription, string errorDetalization)
        {
            if (errorDescription == null)
            {
                throw new ArgumentNullException("errorDescription");
            }

            var updateLog = new UpdateLog
                {
                    Succeed = false,
                    InstallDate = DateTime.Now,
                    ErrorDescription = errorDescription,
                    ErrorDetalization = errorDetalization,
                };
            return updateLog;
        }

        public static UpdateLog CreateSuccessLog(
            IEnumerable<UpdateInformation> appliedUpdates,
            IEnumerable<ChangeLogRecord> changeLog)
        {
            if (appliedUpdates == null)
            {
                throw new ArgumentNullException("appliedUpdates");
            }

            if (changeLog == null)
            {
                throw new ArgumentNullException("changeLog");
            }

            var updateLog = new UpdateLog
                {
                    Succeed = true,
                    InstallDate = DateTime.Now,
                    AppliedUpdates = appliedUpdates.ToArray(),
                    ChangeLog = changeLog.ToArray()
                };
            return updateLog;
        }
    }
}
